package exams.binary;

import java.util.ArrayList;
import java.util.List;

public class WeightedBinaryTreeSolution {

    public List<Integer> sumAllPaths(TreeNode treeNode) {
        List<Integer> res = new ArrayList<>();
        dfs(res, 0, treeNode);
        return res;
    }

    private void dfs(List<Integer> res, int currentSum, TreeNode treeNode) {
        currentSum += treeNode.val;
        if(treeNode.left == null && treeNode.right == null) {
            res.add(currentSum);
            return;
        }
        if(treeNode.left != null) {
            dfs(res, currentSum, treeNode.left);
        }
        if(treeNode.right != null) {
            dfs(res, currentSum, treeNode.right);
        }
    }

    public List<Integer> sumAllPaths(int[][] arr) {
        List<Integer> res = new ArrayList<>();
        dfs(res, 0, arr, 0, 0, 0);
        dfs(res, 0, arr, 0, 2, 0);
        return res;
    }

    private void dfs(List<Integer> res, int currentSum, int[][] arr, int x, int y, int op) {
        currentSum += arr[x][y] - op * arr[x][y+1];

        if(x == arr.length - 1) {
            res.add(currentSum);
            return;
        }
        dfs(res, currentSum, arr, x + 1, 0, y == 0 ? 0 : 1);
        dfs(res, currentSum, arr, x + 1, 2, y == 2 ? 0 : 1);
    }

}
